package org.fuys.coder.infrastructure.util;

import org.fuys.coder.common.exception.BaseException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.common.util
 * @className: LuaScriptLoader
 * @author: WangJing
 * @description: lua脚本加载器
 * @date: 2024/7/26 21:53
 * @version: 1.0
 */
@Service
public class LuaScriptLoader {

    private Map<String,String> scriptMap=new HashMap<>();
    private Map<String,DefaultRedisScript<String>> scriptContentMap=new HashMap<>();
    public Map<String,String> loadLuaScript(){
        ResourcePatternResolver resourcePatternResolver=new PathMatchingResourcePatternResolver();
        String pattern="classpath:luascripts/*.lua";
        Map<String,String> scripts=new HashMap<>();
        try{
            Resource[] resources=resourcePatternResolver.getResources(pattern);
            for (Resource resource : resources) {
                String name = resource.getFilename();
                if(name!=null){
                    final InputStream inputStream = resource.getInputStream();
                    final String scriptContent = readInputStreamToString(inputStream);
                    scripts.put(name,scriptContent);
                    DefaultRedisScript<String> script=new DefaultRedisScript<>();
                    script.setScriptText(scriptContent);
                    script.setResultType(String.class);
                    scriptContentMap.put(name,script);
                }
            }
            return scripts;
        }catch (IOException e){
            throw new BaseException("lua脚本加载失败!");
        }
    }

    private String readInputStreamToString(InputStream inputStream) throws IOException{
        final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        StringBuilder stringBuilder=new StringBuilder();
        String line=null;
        while((line=bufferedReader.readLine())!=null){
            stringBuilder.append(line).append(System.lineSeparator());
        }
        bufferedReader.close();
        return stringBuilder.toString();
    }

    public DefaultRedisScript<String> getScript(String name){
        return scriptContentMap.get(name);
    }

    public String getScriptSha(String name){
        return scriptMap.get(name);
    }

    public void setScriptMap(Map<String,String> map){
        this.scriptMap=map;
    }

}
